package com.gitee.feizns.itrip.personal.utils.bean;

import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.mailer.Mailer;

import java.text.MessageFormat;

/**
 * @author feizns
 * @since 2018/12/26 0026
 */
public class EmailBean {

    /**
     * 发送邮箱用户名
     */
    private String fromName;

    /**
     * 发送邮箱账号
     */
    private String fromEmail;

    /**
     * 主题
     */
    private String subject;

    /**
     * 发送文本，可以使用 {\d+} 占位
     */
    private String text;

    public String getFromName() {
        return fromName;
    }

    public void setFromName(String fromName) {
        this.fromName = fromName;
    }

    public String getFromEmail() {
        return fromEmail;
    }

    public void setFromEmail(String fromEmail) {
        this.fromEmail = fromEmail;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    private Mailer mailer;

    /**
     *
     * @param host 邮箱服务器地址
     * @param port 邮箱服务器端口
     * @param username 用户名
     * @param password 密码
     * @param fromName 发送者用户名
     * @param fromEmail 发生者邮箱
     * @param subject 主题
     * @param text 发送文本
     */
    public EmailBean(String host, Integer port, String username, String password, String fromName, String fromEmail, String subject, String text) {
        this(host, port, username, password);
        this.fromName = fromName;
        this.fromEmail = fromEmail;
        this.subject = subject;
        this.text = text;
    }

    /**
     *
     * @param host 邮箱服务器地址
     * @param port 邮箱服务器端口
     * @param username 用户名
     * @param password 密码
     */
    public EmailBean(String host, Integer port, String username, String password) {
        this.mailer = new Mailer(host, port, username, password);
    }

    private EmailBuilder builder(String... to) {
        return new EmailBuilder()
                .from(fromName, fromEmail)
                .to(to)
                .subject(subject);
    }

    public void send(String to, Object... placeholder) {
        mailer.sendMail(builder(to).text(replace(placeholder)).build());
    }

    public void send(String[] to, Object... placeholder) {
        mailer.sendMail(builder(to).text(replace(placeholder)).build());
    }

    private String replace(Object... placeholder) {
        return MessageFormat.format(text, placeholder);
    }

    @Override
    public String toString() {
        return "EmailBean{" +
                "fromName='" + fromName + '\'' +
                ", fromEmail='" + fromEmail + '\'' +
                ", subject='" + subject + '\'' +
                ", text='" + text + '\'' +
                ", mailer=" + mailer +
                '}';
    }

}
